#!/usr/bin/env python
# -*- coding: utf-8 -*-

from tornado import ioloop
from store_info import relationship, user
import json

relationship_db = relationship()
user_db = user()


async def top_list():
    user_list = []
    relationship_list = []
    user_info_dict = {}
    relationship_info_dict = {}
    top_relationship_list = await relationship_db.get_top(1000, 200)
    for relationship_info in top_relationship_list:
        # 取from to 相同 即回复数高的人
        if relationship_info['from'] != relationship_info['to']:
            continue
        search_user_params = {
            'username': relationship_info['from']
        }
        user_result = await user_db.get(search_user_params)
        if user_result:
            user_info = {
                'id': user_result['username'],
                'name': user_result['username'],
                'thumb': user_result['thumb'] if 'thumb' in user_result else ''
            }
            user_info_dict[user_info['name']] = user_info
        search_user_params = {
            'username': relationship_info['to']
        }
        user_result = await user_db.get(search_user_params)
        if user_result:
            user_info = {
                'id': user_result['username'],
                'name': user_result['username'],
                'thumb': user_result['thumb'] if 'thumb' in user_result else ''
            }
            user_info_dict[user_info['name']] = user_info

        relationship_info_dict[relationship_info['_id']] = {
                'source': relationship_info['from'],
                'target': relationship_info['to'],
                'value': relationship_info['count'],
            }
        # 获取此用户关系最近的9个用户
        user_top_relationship_data = await user_top_relationship(relationship_info['from'], 10)
        if 'user_info_dict' in user_top_relationship_data:
            user_info_dict.update(user_top_relationship_data['user_info_dict'])
        if 'relationship_info_dict' in user_top_relationship_data:
            relationship_info_dict.update(user_top_relationship_data['relationship_info_dict'])

        relationship_data = user_top_relationship_data['relationship_info_dict']

        for relationship_key in relationship_data:
            relationship_info = relationship_data[relationship_key]
            # 获取此用户关系最近的6个用户
            user_top_relationship_data = await user_top_relationship(relationship_info['target'], 7)
            if 'user_info_dict' in user_top_relationship_data:
                user_info_dict.update(user_top_relationship_data['user_info_dict'])
            if 'relationship_info_dict' in user_top_relationship_data:
                relationship_info_dict.update(user_top_relationship_data['relationship_info_dict'])



    for user_id in user_info_dict:
        user_list.append(user_info_dict[user_id])

    for relationship_id in relationship_info_dict:
        relationship_list.append(relationship_info_dict[relationship_id])

    print(json.dumps(user_list))
    print(json.dumps(relationship_list))


async def user_top_relationship(username='', limit=10):
    user_info_dict = {}
    relationship_info_dict = {}
    if not username:
        return user_relationship

    search_params = {'from': username}
    skip = 0
    sort = [('count', -1)]
    user_top_relationship_list = await relationship_db.get_list(search_params, skip, limit, sort)
    search_params['to'] = username
    for sub_relationship_info in user_top_relationship_list:
        search_user_params = {
            'username': sub_relationship_info['from']
        }
        user_result = await user_db.get(search_user_params)
        if user_result:
            user_info = {
                'id': user_result['username'],
                'name': user_result['username'],
                'thumb': user_result['thumb'] if 'thumb' in user_result else '',
            }
            user_info_dict[user_info['name']] = user_info
        search_user_params = {
            'username': sub_relationship_info['to']
        }
        user_result = await user_db.get(search_user_params)
        if user_result:
            user_info = {
                'id': user_result['username'],
                'name': user_result['username'],
                'thumb': user_result['thumb'] if 'thumb' in user_result else '',
            }
            user_info_dict[user_info['name']] = user_info

        relationship_info_dict[sub_relationship_info['_id']] = {
                'source': sub_relationship_info['from'],
                'target': sub_relationship_info['to'],
                'value': sub_relationship_info['count'],
            }
        search_params = {'from': sub_relationship_info['to'], 'to': sub_relationship_info['to']}
        skip = 0
        sort = [('count', -1)]
        user_self_relationship = await relationship_db.get_list(search_params, skip, 1, sort)
        user_self_relationship = user_self_relationship[0]
        relationship_info_dict[user_self_relationship['_id']] = {
                    'source': user_self_relationship['from'],
                    'target': user_self_relationship['to'],
                    'value': user_self_relationship['count'],
                }

    data = {
            'user_info_dict': user_info_dict,
            'relationship_info_dict': relationship_info_dict
            }
    return data

async def get_user_relationship(username='', limit=10):
    if not username:
        return []
    user_info_dict = {}
    relationship_info_dict = {}
    relationship_data = await user_top_relationship(username, limit)
    user_info_dict.update(relationship_data['user_info_dict'])
    relationship_info_dict.update(relationship_data['relationship_info_dict'])
    for sub_relationship_id in relationship_data['relationship_info_dict']:
        sub_relationship_info = relationship_info_dict[sub_relationship_id]
        sub_relationship_data = await user_top_relationship(sub_relationship_info['target'], limit)
        user_info_dict.update(sub_relationship_data['user_info_dict'])
        relationship_info_dict.update(sub_relationship_data['relationship_info_dict'])

    user_list = []
    relationship_list = []
    for user_id in user_info_dict:
        user_list.append(user_info_dict[user_id])
    
    for relationship_id in relationship_info_dict:
        relationship_list.append(relationship_info_dict[relationship_id])
    print(json.dumps(user_list))
    print(json.dumps(relationship_list))

async def print_user_top_relationship(username='', limit=10):
    if not username:
        return []
    search_params = {'from': username}
    skip = 0
    sort = [('count', -1)]
    user_top_relationship_list = await relationship_db.get_list(search_params, skip, limit, sort)
    print("%s 贴吧互动关系为:" % username)
    for sub_relationship_info in user_top_relationship_list:
        if sub_relationship_info['from'] != sub_relationship_info['to']:
            print("%s 互动指数 %s" % (sub_relationship_info['to'], sub_relationship_info['count']))
        else:
            print("%s 活跃指数 %d" % (sub_relationship_info['from'], sub_relationship_info['count']))


if __name__ == '__main__':
    io_loop = ioloop.IOLoop.current()
    # 使用lambda封装传递参数
    io_loop.run_sync(lambda: top_list())
